package com.zx.ymy.net

import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.Utils
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import com.google.gson.GsonBuilder
import com.zx.yixun.util.DataStoreUtil
import okhttp3.MediaType

/**
 *  @ 2019.10.08
 */

class NetWorkHelper private constructor() {

    private val mRetrofit: Retrofit

    init {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        val httpClient = OkHttpClient.Builder()
                .readTimeout(120, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor { chain ->
                    val builder = chain.request().newBuilder()
//                    builder.addHeader("device", DeviceUtils.getModel())
                    if (DataStoreUtil.hasToken()) {
                        builder.addHeader("token", DataStoreUtil.getToken())
                    }
                    builder.addHeader("Accept","application/json")
                    val request = builder.build()
                    Log.d(TAG, "request token:" + DataStoreUtil.getToken())
                    val res = chain.proceed(request)
                    val mediaType = res.body()?.contentType()
                    val content = res.body()?.string()!!
                    Log.d(TAG, "response body:$content")

                    try {
                        val jsonObj = JSONObject(content)
                        if (jsonObj.has("code")) {
                            val code = jsonObj.getInt("code")
                            if (code == 3001 || code == 3002 || code == 3003) {
                            }
                        }
                        if (jsonObj.has("token")) {
                            val token = jsonObj.getString("token")
                            if (!TextUtils.isEmpty(token)) {
                                DataStoreUtil.saveToken(token)
                            }
                        }
                    } catch (e: JSONException) {
                        Log.d("TAG", "json exception")
                    }
//                        return@addInterceptor chain.proceed(request.newBuilder()
//                                .method(request.method(), request.body()).build())
                    return@addInterceptor res.newBuilder().body(okhttp3.ResponseBody.create(
                        MediaType.parse("application/json"), content)).build()
                }
                .build()
        mRetrofit = Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder()
                        .create()))
                .client(httpClient)
                .build()
    }

    fun <T> createApi(cls: Class<T>): T {
        return this.mRetrofit.create(cls)
    }

    companion object {
        @Volatile
        private var instance: NetWorkHelper? = null

        var BaseUrl = "https://www.flydiagram.com/"
//        var BaseUrl = "http://192.168.0.111:8082/"

        private val TAG = "NetHelper"

        fun instance(): NetWorkHelper =
                instance ?: synchronized(this) {
                    instance ?: NetWorkHelper().also {
                        instance = it
                    }
                }
    }

}
























